import { _decorator, AudioClip, AudioSource, Component, director, game, instantiate, Label, macro, Node, Prefab, Size, Tween, tween, UIOpacity, UITransform } from 'cc';
import { GlobalVar } from './GlobalVar';
import { WssCom } from './net/WssCom';
import { C2SEvent, GameEvent, PropUpType } from './EventName';
import { RewardProp } from './commonComp/RewardProp';
import { BossReward } from './commonComp/InterfaceCom';
import { HttpCom } from './net/HttpCom';
import { Config } from './Config';
import { ModelUI } from './ModelUI';
import { WssComAD } from './net/WssComAD';
import { Adventure } from './Adventure/Adventure';
import { WeaponFactory } from './weaponfactory/WeaponFactory';
const { ccclass, property } = _decorator;

@ccclass('GameMain')
export class GameMain extends Component {

    @property([Node])
    pages: Node[] = []

    @property(Prefab)
    rewardPropPre: Prefab = null;
    @property(Node)
    propLayer: Node = null;

    @property(Node)
    toastNode: Node = null;

    @property(Node)
    loadingPage: Node = null;

    @property(Node)
    gamePanel: Node = null;
    @property(AudioClip)
    gamebgm: AudioClip[] = [];
    @property(AudioSource)
    gameAudio: AudioSource = null;

    protected onLoad(): void {
        ModelUI.getInstance().gamePanel = this.gamePanel;
        ModelUI.getInstance().gamePanel.active = false;
    }

    debugMode(){
        director.loadScene("test")
    }

    loadingPageTween: Tween<any> = null;
    protected start(): void {
        this.gameAudio.clip = this.gamebgm[0];
        this.gameAudio.play();
        this.toastNode.getComponent(UIOpacity).opacity = 0;
        this.showPage(null, 0)

        GlobalVar.wss = new WssCom();
        GlobalVar.wss.initWs();

        game.on(C2SEvent.ON_PLAYER_CLICK, this.ON_PLAYER_CLICK, this)

        game.on(GameEvent.SHOW_REWARD_PROPUP, this.SHOW_REWARD_PROPUP, this)

        game.on(GameEvent.SHOW_TOAST, this.SHOW_TOAST, this)

        game.on(GameEvent.SHOW_STORE_PAGE, this.SHOW_STORE_PAGE, this)

        game.on(GameEvent.SHOW_LOADING_PAGE, this.SHOW_LOADING_PAGE, this)

        this.schedule(this.checkWssConnection, 2, macro.REPEAT_FOREVER, 5)
        //this.schedule(this.checkWssADConnection, 2, macro.REPEAT_FOREVER, 1)
    }


    ON_PLAYER_CLICK() {
        let data = {
            cmd: 2
        }
        GlobalVar.wss.sendBinaryMessage(data);
    }

    SHOW_LOADING_PAGE(isShow?: boolean) {
        if (this.loadingPageTween) {
            this.loadingPageTween.stop();
        }
        if (isShow) {

            this.loadingPage.active = true;
            this.loadingPage.getComponent(UIOpacity).opacity = 0;
            this.loadingPageTween = tween(this.loadingPage.getComponent(UIOpacity))
                .delay(0.8)
                .to(0.1, { opacity: 255 })
                .start()
        } else {
            this.loadingPage.active = false;
        }
    }

    SHOW_STORE_PAGE() {
        this.showPage(null, 3);
    }

    checkWssConnection() {

        let readyState = GlobalVar.wss.socket.readyState;
        console.log(readyState, "当前wss状态")
        switch (readyState) {
            case WebSocket.CLOSED:
                game.emit(GameEvent.SHOW_TOAST, "Connecting to server")
                window.location.reload();
                //game.restart();
                //GlobalVar.wss.initWs();
                break;

        }
    }
    checkWssADConnection() {
        let readyState = GlobalVar.wss.socket.readyState;
        console.log(readyState, "当前wss状态")
        switch (readyState) {
            case WebSocket.CLOSED:
                game.emit(GameEvent.SHOW_TOAST, "Connecting to server")
                //window.location.reload();
                //game.restart();
                //GlobalVar.wss.initWs();
                break;

        }
    }

    toastTween: Tween<any> = null;

    SHOW_TOAST(str?: string) {
        if (this.toastTween) {
            this.toastTween.stop();
        }
        this.toastNode.getComponent(UIOpacity).opacity = 255;
        this.toastNode.getComponentInChildren(Label).string = str;
        this.toastNode.children[0].getComponent(UITransform).setContentSize(new Size(str.length * 13, 70))
        //this.toastNode.getComponent(UITransform).contentSize.width = str.length * 13   
        this.toastTween = tween(this.toastNode.getComponent(UIOpacity))
            .delay(2)
            .to(2, { opacity: 0 })
            .start();
    }

    SHOW_REWARD_PROPUP(data?: any, type?: PropUpType) {
        game.emit(GameEvent.FIRE_CTRL, false);
        let prop = instantiate(this.rewardPropPre);
        this.propLayer.addChild(prop);

        let com = prop.getComponent(RewardProp);
        let gold = "0"
        let ticket = '0'

        let tipInfo = ""
        let btnInfo = ""
        let cb: Function = null
        try {

            switch (type) {
                case PropUpType.BossReward:
                    data.body.forEach((e, i) => {
                        if (e.name) {

                            if (e.name.toLowerCase() == "gold") {
                                gold = e.value;
                            }

                            if (e.name.toLowerCase() == "ticket") {
                                ticket = e.value;
                            }
                        }

                    })
                    tipInfo = "You successfully killed the world boss."
                    btnInfo = "Keep fighting"
                    cb = () => {
                        game.emit(GameEvent.FIRE_CTRL, true);
                        HttpCom.getBossAward();
                    }
                    break;
                case PropUpType.AirDropReward:
                    data.data.forEach((e, i) => {
                        if (e.name) {

                            if (e.name.toLowerCase() == 'gold') {
                                gold = e.value;
                            }

                            if (e.name.toLowerCase() == "ticket") {
                                ticket = e.value;
                            }
                        }

                    })
                    tipInfo = ""
                    btnInfo = "OK"
                    cb = () => {
                        game.emit(GameEvent.FIRE_CTRL, true);
                    }
                    break;
                case PropUpType.CDKReward:
                    data.data.forEach((e, i) => {
                        if (e.name) {

                            if (e.name.toLowerCase() == 'gold') {
                                gold = e.value;
                            }

                            if (e.name.toLowerCase() == "ticket") {
                                ticket = e.value;
                            }
                        }

                    })
                    tipInfo = ""
                    btnInfo = "OK"
                    cb = () => {
                        game.emit(GameEvent.FIRE_CTRL, true);
                    }
                    break;
                case PropUpType.TaskReward:
                    tipInfo = "You successfully killed the world boss."
                    btnInfo = "Keep fighting"
                    cb = () => {
                        game.emit(GameEvent.FIRE_CTRL, true);
                    }
                    break;
                default:
                    tipInfo = ""
                    btnInfo = "OK"
                    cb = () => {
                        game.emit(GameEvent.FIRE_CTRL, true);
                    }
            }
        }

        catch (e) {

        }
        com.initView(gold, ticket, cb, tipInfo, btnInfo);

    }

    showPage(event, index) {
        this.pages.forEach((e, i) => {

            e.active = false
        })

        this.pages[index].active = true;
        if (this.pages[index].getComponent(Adventure)) {
            this.pages[index].getComponent(Adventure).initView();
            if (this.gameAudio.clip == this.gamebgm[0]) {
                this.gameAudio.stop();
                this.gameAudio.clip = this.gamebgm[1];
                this.gameAudio.play();
            }
        } else {
            if (this.gameAudio.clip == this.gamebgm[1]) {
                this.gameAudio.stop();
                this.gameAudio.clip = this.gamebgm[0];
                this.gameAudio.play();
            }
        }
        if (this.pages[index].getComponent(WeaponFactory)) {
            this.pages[index].getComponent(WeaponFactory).initView();
        }
    }






    update(deltaTime: number) {

    }
}


